import {Button, Card, Form, Input, InputNumber, Popover, Switch} from "antd";
import {useComponentsStore} from "../../../stores/components.tsx";
import {ComponentSetter, FormRule, useComponentConfigStore} from "../../../stores/component-config.tsx";
import {useEffect, useState} from "react";
import {renderComponentType} from "./utils/renderComponentType.tsx";
import {debounceHandle} from "../../../utils/throttle.ts";
import FormItem from "antd/es/form/FormItem";
import {DeleteTwoTone} from "@ant-design/icons";


const FormComponent = ['Input', "EmailInputDev", "TextInput", 'Select', 'Radio', 'Checkbox', 'CheckboxInput', 'TextArea', 'DatePicker', 'TimePicker', 'Slider', 'Rate', 'Upload', 'Transfer', 'Cascader', 'AutoComplete', 'InputNumber', 'Slider', 'Rate', 'Upload', 'Transfer']

const ComponentAttr = () => {

    const [form] = Form.useForm()
    const {currentComponentId, currentComponent, updateComponentProps} = useComponentsStore();
    const {componentConfig, FormRule} = useComponentConfigStore();
    const [open, setOpen] = useState(false)

    useEffect(() => {
        form?.resetFields()
        form?.setFieldsValue({...currentComponent?.props});
    }, [currentComponent])

    if (!currentComponentId || !currentComponent) return null;

    async function valueChange() {
        if (currentComponentId) {
            debounceHandle(() => {
                updateComponentProps(currentComponentId, form.getFieldsValue());
            }, 500)
        }
    }

    // 渲染表单元素
    function renderFormElement(setter: ComponentSetter) {
        // 根据不同的组件类型，渲染不同的表单组件
        return renderComponentType(setter)
    }


    // 渲染表单验证规则
    const renderFormRule = () => {
        const data = currentComponent?.props?.rule || [];
        return (
            <FormItem noStyle>
                <Form.List
                    name={'rule'}
                    key={currentComponentId + "-" + data.length}
                    initialValue={currentComponent?.props?.rule}
                >
                    {(fields, {remove, add}) => (
                        <>
                            {
                                fields.map(({key, name, ...restField}) => {
                                    const ruleData = data[key];
                                    if (!ruleData) return null;
                                    return (
                                        <Card
                                            extra={<DeleteTwoTone onClick={() => remove(name)}
                                                                  style={{cursor: "pointer"}} />}
                                            key={key}
                                            title={ruleData.label}
                                            className={'mb-6'}
                                        >
                                            {renderValidationFields(ruleData, restField, name)}
                                        </Card>
                                    );
                                })
                            }
                            {FormComponent.includes(currentComponent.name) && <Popover arrow={false} open={open}
                                                                                       content={<ul
                                                                                           onMouseLeave={() => setOpen(false)}>{ruleList(add)}</ul>}
                                                                                       trigger="hover"
                                                                                       className={'w-full'}>
                                <Button type="primary" onMouseOver={() => setOpen(true)}> +
                                    添加自定义验证规则</Button>
                            </Popover>}


                        </>
                    )}
                </Form.List>
            </FormItem>
        );
    };

    const renderValidationFields = (ruleData: any, restField: any, name: any) => {
        if (ruleData.label === "必填校验") {
            return (
                <>
                    <FormItem {...restField} name={[name, 'required']} label={'是否必填'}>
                        <Switch />
                    </FormItem>
                    <FormItem {...restField} name={[name, 'message']} label={'错误提示'}>
                        <Input placeholder={'错误提示'} />
                    </FormItem>
                </>
            );
        } else if (ruleData.label === "长度校验") {
            return (
                <>
                    <FormItem {...restField} name={[name, 'min']} label={'最小长度'}>
                        <InputNumber placeholder={ruleData.min} />
                    </FormItem>
                    <FormItem {...restField} name={[name, 'max']} label={'最大长度'}>
                        <InputNumber placeholder={ruleData.max} />
                    </FormItem>
                    <FormItem {...restField} name={[name, 'message']} label={'错误提示'}>
                        <Input placeholder={'错误提示'} />
                    </FormItem>
                </>
            );
        } else {
            return (
                <>
                    <FormItem {...restField} name={[name, 'pattern']} label={'规则校验'}>
                        <Input placeholder={'eg:^[0-9]+$'} />
                    </FormItem>
                    <FormItem {...restField} name={[name, 'message']} label={'错误提示'}>
                        <Input placeholder={"错误提示"} />
                    </FormItem>
                </>
            );
        }
    };

    // 添加自定义验证规则
    const addRules = (add: any, item: FormRule) => {
        setOpen(open => !open)
        if (item.label === "必填校验") {
            add({
                required: item.rule[0].defaultValue,
                message: `${item.rule[1].defaultValue}`,
                label: item.label
            })
        } else if (item.label === "长度校验") {
            add({
                min: item.rule[0].defaultValue,
                max: item.rule[1].defaultValue,
                message: item.rule[2].defaultValue,
                label: item.label
            })
        } else {
            add({
                pattern: item.rule[0].defaultValue,
                message: `${item.rule[1].defaultValue}`,
                placeholder: `${item.rule[0].placeholder}`,
                label: item.label
            })
        }

    }
    // 渲染表单验证规则选择列表
    const ruleList = (add: any) => {
        return FormRule.map((item, index) => {
            return <li onClick={() => addRules(add, item)} key={item.label + index + ""}
                       className={'w-full h-8 leading-[16px] p-2  cursor-pointer hover:bg-[#f5f5f5]'}>
                {item.label}
            </li>
        })
    }

    return (
        <div>
            <Form
                form={form}
                onValuesChange={valueChange}
                labelCol={{span: 7}}
                wrapperCol={{span: 16}}
                className={'pl-[20px]'}
                labelAlign={'left'}
                labelWrap={true}
            >
                <Form.Item label="组件id">
                    <Input value={currentComponent.id} disabled />
                </Form.Item>
                <Form.Item label="组件名称">
                    <Input value={currentComponent.name} disabled />
                </Form.Item>
                <Form.Item label="组件描述">
                    <Input value={currentComponent.desc} disabled />
                </Form.Item>
                <Form.Item label="字段名称" name={'name'}>
                    <Input />
                </Form.Item>
                {/* 渲染组件属性 */}
                {
                    componentConfig[currentComponent.name]?.setter?.map((setter, index) => (
                        <FormItem key={setter.name + index} noStyle>
                            {renderFormElement(setter)}
                        </FormItem>
                    ))
                }
                {renderFormRule()}
            </Form>
        </div>
    );
};

export default ComponentAttr;